<template>
  <div class="purchase-order-list">
    <div class="header">
      <h2>进货单管理</h2>
      <el-button type="primary" @click="$router.push('/purchase-orders/new')">
        新建进货单
      </el-button>
    </div>

    <el-table :data="orders" style="width: 100%" v-loading="loading">
      <el-table-column prop="order_number" label="订单号" width="180" />
      <el-table-column prop="dealer_name" label="经销商" width="180" />
      <el-table-column prop="status" label="订单状态">
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.status)">
            {{ getStatusText(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="order_date" label="下单日期" width="180">
        <template #default="{ row }">
          {{ formatDate(row.order_date) }}
        </template>
      </el-table-column>
      <el-table-column prop="notes" label="备注" show-overflow-tooltip />
      <el-table-column label="操作" width="120" fixed="right">
        <template #default="{ row }">
          <el-button 
            size="small" 
            @click="viewDetails(row.id)"
          >
            查看详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import PurchaseOrderService from '@/api/purchaseOrderService'

const router = useRouter()
const orders = ref([])
const loading = ref(false)

// 获取订单列表
async function fetchOrders() {
  loading.value = true
  try {
    const response = await PurchaseOrderService.getAllOrders()
    orders.value = response.data
  } catch (error) {
    console.error('Error fetching orders:', error)
    ElMessage.error('获取订单列表失败')
  } finally {
    loading.value = false
  }
}

// 查看详情
function viewDetails(id) {
  router.push(`/purchase-orders/${id}`)
}

// 状态显示相关
function getStatusType(status) {
  const types = {
    pending: 'warning',
    completed: 'success',
    cancelled: 'danger'
  }
  return types[status] || 'info'
}

function getStatusText(status) {
  const texts = {
    pending: '待处理',
    completed: '已完成',
    cancelled: '已取消'
  }
  return texts[status] || status
}

function formatDate(date) {
  return new Date(date).toLocaleString()
}

onMounted(() => {
  fetchOrders()
})
</script>

<style scoped>
.purchase-order-list {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
}

.el-tag {
  text-align: center;
  min-width: 80px;
}
</style> 